#include "snake.h"
u8 g[24][32];
u16 food_x = 10, food_y = 10;
void show(Snake snake)
{
    u16 i;
    fade(food_x, food_y,snake.size,BLUE);
    for (i = 1; i <= snake.nums; i++)
    {
        if(i==1)
        fade(snake.occ[0][i], snake.occ[1][i], snake.size,GREEN);
        else
        fade(snake.occ[0][i], snake.occ[1][i], snake.size,RED);
    }
  
}
void fade(u16 x, u16 y, u16 size,u16 color)
{
    LCD_Fill(x, y, x + size, y + size, color);
}
u8 move(Snake *snake, u8 t)
{
    u16 d, i,x,y;
    if(t&&(abs(t-snake->dir)%2))snake->dir = t;
    d = snake->dir;
    for (i = snake->nums; i > 1; i--)
    {
        snake->occ[0][i] = snake->occ[0][i - 1];
        snake->occ[1][i] = snake->occ[1][i - 1];
    }
    if (d == 3)
    {
        snake->occ[0][i] -= snake->size;
    }
    else if (d == 1)
    {
        snake->occ[0][i] += snake->size;
    }
    else if (d == 2)
    {
        snake->occ[1][i] += snake->size;
    }
    else if (d == 4)
    {
        snake->occ[1][i] -= snake->size;
    }
    x = snake->occ[0][i],y = snake->occ[1][i];
    if(abs(x-food_x)<10&&abs(y-food_y)<10)
    {
        snake->nums++;
        for(i = snake->nums;i>1;i--)
        {
            snake->occ[0][i] = snake->occ[0][i-1];
            snake->occ[1][i] = snake->occ[1][i-1];
        }
        snake->occ[0][i] = food_x;
        snake->occ[1][i] = food_y;
        food(*snake);
    }
    //if(x < 0 || y < 0 || x > 24 || y > 32)return -1;
    
    if(snake->occ[0][1] < -1)snake->occ[0][1] = 230;
    if(snake->occ[0][1] > 230)snake->occ[0][1] = 0;
    if(snake->occ[1][1] < -1)snake->occ[1][1] = 310;
    if(snake->occ[1][1] > 310)snake->occ[1][1] = 0;

    for(i = 3; i <= snake->size; i++)
    {

        if(abs(snake->occ[0][i] - snake->occ[0][1])<10&&abs(snake->occ[1][i] - snake->occ[1][1])<10)return 1;
    }
    return 0;

}
void snake_init(Snake *snake)
{
    snake->size = 10;
    snake->nums = 3;
    snake->dir = 2;
    snake->occ[0][snake->nums] = 120;
    snake->occ[1][snake->nums] = 140;
    snake->occ[0][snake->nums] = 130;
    snake->occ[1][snake->nums] = 140;
    snake->occ[0][snake->nums] = 140;
    snake->occ[1][snake->nums] = 140;
}
void food(Snake snake)
{
    u8 i,j,xx,yy;
    const int x = 24,y = 32;
    u16 n = x * y;
    int tmp = 50;
    for(i = 0; i < x; i++)
    for(j = 0; j < y; j++)
    g[x][y] = 0;
    
    for(i = 1; i <= snake.size; i++)
    {
        xx = snake.occ[0][i] / snake.size;
        yy = snake.occ[1][i] / snake.size;
        g[xx][yy] = 1;
    }
    RNG_Init();

    tmp = Get_RandomRange(0,n - 1);
    for(i = 0; i < x; i++)
    {
        for(j = 0; j < y; j++)
        {
            if(!g[i][j])
            {
                tmp--;
                if(!tmp)
                {
                    food_x = i * snake.size;
                    food_y = j * snake.size;
                    return;
                }
            }
        }
    }
}
